import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:image/image.dart' as image_library;
import 'package:path_provider/path_provider.dart';

class ImageUtils {
  static Future<String?> compressImage(String path, double length, int quality) async {

    // 重复压缩有可能会导致图片越来越大
    // 改用修改quality

    if (File(path).lengthSync() < length) {
      return path;
    }

    if (quality <= 10) {
      return path;
    }

    debugPrint('当前quality： $quality');
    debugPrint('初始图片length：${File(path).lengthSync()}');

    String targetPath = "${(await getApplicationDocumentsDirectory()).path}/image_compress.jpeg";
    if (File(targetPath).existsSync()) {
      File(targetPath).deleteSync();
    }

    XFile? imageFile =  await FlutterImageCompress.compressAndGetFile(
        path,
        targetPath,
        quality: quality,
        minHeight: 768,
        minWidth: 768
    );
    if (imageFile == null) return null;

    debugPrint('压缩后 file path: ${imageFile.path}');
    debugPrint('压缩后 file length: ${await imageFile.length()}, length: $length');

    if ((await imageFile.length()) > length) {
      debugPrint('进行进一步压缩 ===');
      quality -= 10;
      return compressImage(path, length, quality);
    } else {
      debugPrint('after compressImage length: ${File(imageFile.path).lengthSync()}');
      return imageFile.path;
    }
  }
}